const app = getApp()
Page({

  data: {
    language: {},
    getMarketPrice: "",
    timeData: {},
    goodsInfo: {
      thumb_url: [
        "https://img.yzcdn.cn/upload_files/2020/03/31/Fh0JRCgClmgcMRaD9elw3ZgJDN-2.jpg",
        "https://img.yzcdn.cn/upload_files/2020/03/31/FhaAiL_aSqAQBkZfQa1ogFI7z3NF.jpg",
      ],
    },
    goods_id:"",
    option_type:"",
    record_id:"",

    radioChoose:"",
    showChoose: false,
    dispatch_types: [],
    has_many_goods: [],
    goodsDescription: "",
    show: false,
    share: 0,
    language: "",
    list: [],
    carts: [],
    details: {},
    Height: '1100rpx',
    nums: 0,
    index_goods: 0, //当前商品索引
    activity_gid: "",
    current_page: 1,
    last_page: 1,

    goodsPopupShow: false,
    specsShow: false,
    hand_goods_obj: {},
    carList: [],
    hand_goods_id: "",
    message_card: "",

    showKefu: false,
    customer_open: "",
    cservice: "",
    service_mobile: "",
    service_QRcode: "",

    popThumb: "",
    popTitle: "",
    popNum: 0,
    popPrice: "",
    show2: false,
    goodsInfo: {},
    specid: "",
    has_many_options: [],
    current_index: 0,
    gift_card_record_id: ''
  },
  lifetimes: {
    ready() {
      try {
        wx.getStorage({
          key: "langIndex",
          success: (res) => {
            console.log(res.data, 888);
            this.setData({ language: res.data.en });
          },
        });
        wx.getStorage({
          key: "yz_basic_info",
          success: (res) => {
            this.setData({
              getMarketPrice: res.data.lang.goods.market_price,
              getprice: res.data.lang.goods.price,
            });
          },
        });
      } catch (e) {
        console.log(e);
      }
    },
  },
 /**
   * 生命周期函数--监听页面加载
   * op:操作  1：激活 2:绑定 3:兑换 4:转赠 
   */
  onLoad: function (options) {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en,
      goods_id: options.goods_id || '',
      option_type: options.option_type || '',
      record_id: options.record_id || '',
      gift_card_record_id: options?.gift_card_record_id || ''
      
    })
    this.getGoodsDetails(options.goods_id)
  },
  /**
   * 组件的方法列表
   */
  methods: {
    popupSpecsbtn(evt) {
      console.log(evt);
      this.setData({ show: false });
    },
    onChangeTime(e) {
      this.setData({
        timeData: e.detail,
      });
    },
    addCart() {
      this.triggerEvent("addCart", this.data.goodsInfo);
    },
  },
  
  toBuy() {
    this.submitGoods();
  },
  goodsDetailCartAdd() {
    this.data.list.forEach(item => {
      if(item.id == this.data.activity_gid){
        if(item.has_option == 1){
          let json = {
            currentTarget:{
              dataset:{

              }
            }
          }
          this.selectOption(item.id,i,item)
          this.setData({
            goodsPopupShow: false,
            specsShow: false,
          });
        }else{
          this.setData({
            goodsPopupShow: false,
            specsShow: true,
          });
        }
      }
    })
  },
  getGoodsDetails(goodsId) {
    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    console.log("stsssssssss", urlStr)

    app._postNetWork({
      url: urlStr,
      data: {
        id: goodsId
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            complete: (resC) => {
              if (resC.confirm) {
                wx.navigateBack({delta: -1})
              }
            }
          })
          return
        }  
        let name = "";


        this.setData({
          goodsInfo: res.data.get_goods,
        });
      },
    });
  },
  selectOption(e) {
    console.log(e);
    optionsId = "";
    specsManage = [];
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    this.setData({
      specid: '',
      current_index: index,
      activity_gid: item.id,
      popTitle: item.title,
      popPrice: item.price,
      popThumb: item.thumb,
      show2: true,
      popNum: 0,
    })

    let urlStr = app.getNetAddresss("goods.goods.get-goods-page");
    app._postNetWork({
      url: urlStr,
      data: {
        id: Number(item.id)
      },
      success: resdata => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        this.setData({
          goodsInfo: res.data.get_goods,
          has_many_options: this.data.has_many_options.concat(res.data.get_goods.has_many_options)
        });
        if (!this.data.specid.length) {
          let popPrice = this.data.goodsInfo.min_price + "-" + this.data.goodsInfo.max_price; // 设置默认价格
          if (this.data.goodsInfo.point_goods) {
            popPrice = this.data.goodsInfo.point_goods.min_point + "-" + this.data.goodsInfo.point_goods.max_point; //设置默认价格
          }
          this.setData({
            popPrice: popPrice,
          });
        }
        this.setData({
          goodsDescription: "请选择",
        });
        let goodsDescription;
        for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
          goodsDescription = this.data.goodsDescription;
          goodsDescription += "" + this.data.goodsInfo.has_many_specs[i].title;
        }
        this.setData({
          goodsDescription,
        });

        if (!this.data.optionsId) {
          // 默认选择第一个
          for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
            if (this.data.goodsInfo.goods_option_ids && this.data.goodsInfo.goods_option_ids.length >= 0) {
              for (let j = 0; j < this.data.goodsInfo.has_many_specs[i].specitem.length; j++) {
                if (this.data.goodsInfo.has_many_specs[i].specitem[j].id == Number(this.data.goodsInfo.goods_option_ids[i])) {
                  this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[j], "first", i);
                }
              }
            } else {
              this.selectSpecs(this.data.goodsInfo.has_many_specs[i].specitem[0], "first", i);
            }
          }
        }

      }
    })
    // this.showGoodPup(item.id, true, item, index);
  },
  // 提交订单
  submitGoods() {
    console.log("this.data.record_id : ",this.data.record_id )
    let urlStr = `/packageD/buy/myOrder_v2/myOrder_v2?&tag=giftcard_code_activate&record_id=${this.data.record_id}&goods_id=${this.data.goods_id}&gift_card_record_id=${this.data.gift_card_record_id}`;
    wx.navigateTo({
      url: urlStr
    });
  },
  // 界面选择规格触发事件
  selectSpecs(e, str, i) {
    let data = {};
    let id = 0;

    if (str == "first") {
      data = e;
      id = e.id;
    } else {
      data = e.target.dataset.item || e.currentTarget.dataset.item;

      id = e.target.dataset.id || e.currentTarget.dataset.id;
    }

    // 处理选择池
    this.manageSpecs(data);

    // 处理规格组合选择状态
    this.setGoodsSpecs(data);

    // 设置选择规格后的 价格、照片、库存
    this.setGoodsSpecsChangeInfo(id);

  },

  // 处理选择池
  manageSpecs(data) {
    var specsObject = {};
    specsObject.id = data.id;
    specsObject.specid = data.specid;
    specsObject.title = data.title;

    if (specsManage.length > 0) {
      for (let i = 0; i < specsManage.length; i++) {
        if (specsManage[i].specid == specsObject.specid) {
          specsManage.splice(i, 1);
        }
      }
      specsManage.push(specsObject);
    } else {
      specsManage.push(specsObject);
    }

    // 排序
    if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
      var newSpecsManage = [];
      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goodsInfo.has_many_specs[i].id == specsManage[j].specid) {
            newSpecsManage.push(specsManage[j]);
            break;
          }
        }
      }
      specsManage = newSpecsManage;
    }
    this.setGoodsDescription();
  },

  // 处理goodsDescription 数据
  setGoodsDescription() {
    var description = "";
    // 相等代表全选了 体现语句
    if (specsManage.length == this.data.goodsInfo.has_many_specs.length) {
      description = "已选择 ";
      for (let i = 0; i < specsManage.length; i++) {
        description += specsManage[i].title + " ";
      }
      this.setData({
        goodsDescription: description,
      });
    } else {
      description = "请选择 ";

      for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
        for (let j = 0; j < specsManage.length; j++) {
          if (this.data.goodsInfo.has_many_specs[i].id != specsManage[j].specid) {
            description += this.data.goodsInfo.has_many_specs[i].title + " ";
            break;
          }
        }
      }
      this.setData({
        goodsDescription: description,
      });
    }
  },

  // 处理规格组合选择状态 过滤数据
  setGoodsSpecs(specs) {
    for (let i = 0; i < this.data.goodsInfo.has_many_specs.length; i++) {
      if (specs.specid != this.data.goodsInfo.has_many_specs[i].id) {
        this.setGoodsSpecsStatus(this.data.goodsInfo.has_many_specs[i].specitem, specs.id);
      }
    }
  },

  // 处理规格组合选择状态 处理状态 specitem 组合数组(未选中的) id当前选中的ID 根据ID 组合算是否有当前组合
  setGoodsSpecsStatus(specitem, id) {
    let options = []; // 数据池

    for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
      let _specs = this.data.goodsInfo.has_many_options[i].specs.split("_");
      // 判断是否包含
      for (let j = 0; j < _specs.length; j++) {
        if (_specs[j] == id) {
          options.push(this.data.goodsInfo.has_many_options[i]);
        }
      }
    }

    for (let m = 0; m < options.length; m++) {
      let _specs = options[m].specs.split("_");
      for (let y = 0; y < _specs.length; y++) {
        if (_specs[y] != id && options[m].stock == 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = true;
            }
          }
        } else if (_specs[y] != id && options[m].stock > 0) {
          for (let n = 0; n < specitem.length; n++) {
            if (_specs[y] == specitem[n].id) {
              specitem[n].c = false;
            }
          }
        }
      }
    }
  },

  // 设置选择规格后的 价格、照片、库存
  setGoodsSpecsChangeInfo(id) {
    let popPrice = "";
    // 根据ID 排序 specsManage.sort()
    specsManage.sort(function (a, b) {
      return a.id - b.id;
    });
    if (specsManage.length === this.data.goodsInfo.has_many_specs.length) {
      let goodsSpecs = "";
      for (let j = 0; j < specsManage.length; j++) {
        goodsSpecs += specsManage[j].id + "_";
      }
      goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"
      this.setData({
        specid: goodsSpecs,
      });
      for (let i = 0; i < this.data.goodsInfo.has_many_options.length; i++) {
        if (goodsSpecs === this.setGoodsSpecsBySort(this.data.goodsInfo.has_many_options[i].specs)) {
          if (this.data.goodsInfo.point_goods) {
            popPrice = this.data.goodsInfo.point_goods.point_option[i].goods_point; //设置默认价格
          } else {
            popPrice = this.data.goodsInfo.has_many_options[i].product_price; //设置默认价格
          }
          console.log(popPrice, "popPrice-434");
          this.setData({
            popPrice: popPrice, // 设置价格
          });


          let popThumb = app._isTextEmpty(this.data.goodsInfo.has_many_options[i].thumb) ? this.data.goodsInfo.thumb : this.data.goodsInfo.has_many_options[i].thumb; // 设置图片
          this.setData({
            popThumb,
          });

          optionsId = this.data.goodsInfo.has_many_options[i].id; // 设置规格ID，用于生成订单
          break;
        }
      }

    } else {
      let goodsSpecs = "";
      for (let j = 0; j < specsManage.length; j++) {
        goodsSpecs += specsManage[j].id + "_";
      }
      this.setData({
        specid: goodsSpecs,
      });
    }

    let _goods = this.data.has_many_goods.filter(item => item.option_id == optionsId)
    console.log(optionsId, "optionsId====");
    console.log(_goods, "_goods===-501");
    if (_goods.length == 0) {
      this.setData({
        popNum: 0
      })
    } else {
      this.setData({
        popNum: _goods[0].total
      })
    }

  },

  // 处理商品goodsSpecs 并排序 新方法
  setGoodsSpecsBySort(specs) {
    let _specs = specs.split("_"); // 先变成数组
    // _specs.sort();//排序
    _specs.sort(function (a, b) {
      return a - b;
    });

    // 在组装回去
    let goodsSpecs = "";
    for (let j = 0; j < _specs.length; j++) {
      goodsSpecs += _specs[j] + "_";
    }
    goodsSpecs = goodsSpecs.substring(0, goodsSpecs.length - 1); // 处理"_"

    return goodsSpecs;
  },
  
});
